package com.graduationproject.Util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import java.security.Key;
import java.util.Date;
import java.util.function.Function;

@Component
public class Jwt {
    private static final Key SECRET_KEY = Keys.secretKeyFor(SignatureAlgorithm.HS256);
    private static final long EXPIRATION_TIME = 86400000; // 24小时

    /**
     * 生成JWT
     * @param username
     * @param // role  角色
     * @return
     */
    public  String generateToken(String username) {
        String compact = Jwts.builder()  // 1. 创建JWT构建器
                .setSubject(username)  // 2. 设置主题(通常是用户标识)
//                .claim("role", role)  // 3. 添加自定义声明(角色)
                .setIssuedAt(new Date())  // 4. 设置签发时间
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))  // 5. 设置过期时间
                .signWith(SECRET_KEY)  // 6. 使用密钥签名
                .compact();// 7. 生成最终的Token字符串
        return "Bearer " + compact;
    }

    /**
     * 验证JWT
     * @param token
     * @return
     */
    public  boolean validateToken(String token) {
        try {
            // 1. 构建JWT解析器并验证Token
            Jws<Claims> claims = Jwts.parserBuilder()
                    .setSigningKey(SECRET_KEY)  // 设置签名密钥
                    .build()  // 构建解析器
                    .parseClaimsJws(token);  // 解析并验证Token
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 验证令牌是否有效
     * @param token JWT令牌
     * @param userDetails 用户详情
     * @return 是否有效
     */
//    public Boolean validateToken(String token, UserDetails userDetails) {
//        final String username = getUsernameFromToken(token);
//        return (username.equals(userDetails.getUsername()));
//    }


    /**
     * 从Token中获取username
     * @param token
     * @return
     */
    public  String getUsernameFromToken(String token) {
        try {
            Jws<Claims> claimsJws = Jwts.parserBuilder()
                    .setSigningKey(SECRET_KEY)
                    .build()
                    .parseClaimsJws(token);

            // 获取subject字段，即username
            return claimsJws.getBody().getSubject();
        } catch (Exception e) {
            // Token无效或过期等异常处理
            throw new RuntimeException("Invalid token: " + e.getMessage());
        }
    }

    /**
     * 从请求里获取token
     * @param request
     * @return
     */
    private static String getToken(HttpServletRequest request) {
        final String AUTH_HEADER = "Token";
        final String TOKEN_PREFIX = "Bearer ";  // 注意后面有个空格

        String authorization = request.getHeader("AUTH_HEADER");
        if(authorization != null && authorization.startsWith("TOKEN_PREFIX")) {
            return authorization.substring(TOKEN_PREFIX.length());
        }
        return null;
    }
}
